package com.ayou.healthmanagement.config;

import com.ayou.healthmanagement.utils.JwtUtils;
import com.ayou.healthmanagement.utils.RedisUtil;
import com.ayou.healthmanagement.service.HealthUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HealthUserService healthUserService;

    /**
     * 前置处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("后台拦截");
        //获取用户token
        String token = request.getHeader("token");
//        System.out.println(token);
        //通过token解析出用户ID
        String userId = JwtUtils.getId(token);
        //获取缓存中token
        Object t = redisUtil.get(userId);
//        System.out.println("redis中的token="+t);
        if(t == null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            //响应内容
            writer.print(401);
            writer.close();
            //返回false，拦截
            return false;
        }
        //续期半小时
        redisUtil.set(userId,token,1800);
        //返回true，放行
        return true;
    }
}
